package xyz.blushyes.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import xyz.blushyes.dao.UserInfoDao;
import xyz.blushyes.entity.UserInfo;
import xyz.blushyes.request.AuthRequest;
import xyz.blushyes.service.TokenGenerator;
import xyz.blushyes.service.UserInfoService;

import static xyz.blushyes.constant.AuthCost.*;

@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl extends ServiceImpl<UserInfoDao, UserInfo> implements UserInfoService {
    private final StringRedisTemplate stringRedisTemplate;
    private final TokenGenerator tokenGenerator;

    @Override
    public String login(AuthRequest request) {
        // 查询用户信息
        UserInfo userInfo = lambdaQuery()
                .eq(UserInfo::getUsername, request.getUsername())
                .eq(UserInfo::getPassword, request.getPassword())
                .one();

        // 未查询到用户，登录失败直接返回
        if (null == userInfo) {
            throw new RuntimeException(LOGIN_ERROR);
        }

        // 生成 token
        String token = tokenGenerator.generatorToken();

        // 存redis
        // TODO 先简单存一下用户名
        stringRedisTemplate.opsForValue().set(TOKEN_PREFIX + token, userInfo.getUsername());

        return token;
    }
}

